package com.bankcomm.ui.views;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.offstore.OffStoreDB;
import com.rytong.tools.offstore.OffStoreDownload;
import com.rytong.tools.utils.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DropGridAdapter extends BaseAdapter {
	// 为了加快速度，在内存中开启缓存
	public static Map<String, Bitmap> bitmapCache = new HashMap<String, Bitmap>();
	private static Context context;
	public ArrayList<Map<String, Object>> lstDate;
	private int holdPosition;

	private Animation animation;
	private boolean isChanged = false;
	private boolean ShowItem = false;

	/**
	 * 标记是编辑状态，true显示删除图标，false不显示
	 * */
	public static boolean isInEdit = false;
	/**
	 * 标记是否是"我的首页"频道
	 * */
	private boolean isHome = false;
	/**
	 * 标记是否显示"添加"item
	 * */
	//private boolean isShowAdd = true;
	public DropGridAdapter(Context mContext, boolean isHome,
			ArrayList<Map<String, Object>> list) {
		DropGridAdapter.context = mContext;
		lstDate = list;
		this.isHome = isHome;
		if (null == lstDate) {
			lstDate = new ArrayList<Map<String, Object>>();
		}

		if (null == animation) {
			animation = AnimationUtils.loadAnimation(mContext,
					R.anim.grid_shake);
		}
	}

	@Override
	public int getCount() {
		return lstDate.size();
	}

	@Override
	public Object getItem(int position) {
		return lstDate.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("unchecked")
	public void exchange(int startPosition, int endPosition) {
		holdPosition = endPosition;
		Object startObject = getItem(startPosition);

		if (startPosition < endPosition) {
			lstDate.add(endPosition + 1, (Map<String, Object>) startObject);
			lstDate.remove(startPosition);
		} else {
			lstDate.add(endPosition, (Map<String, Object>) startObject);
			lstDate.remove(startPosition + 1);
		}
		isChanged = true;
		notifyDataSetChanged();
	}

	public void showDropItem(boolean showItem) {
		//this.isShowAdd = showItem;
		this.ShowItem = showItem;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		String id = String.valueOf(lstDate.get(position).get("id"));
		String newChannel = String.valueOf(lstDate.get(position).get("user_id"));
		//-------判断图片大小并进行缩放 mod by zhaobin start--------
		int localWidth = LPUtils.getCurrentBitmapWidth();
		int localHeight = LPUtils.getCurrentBitmapHeight();
		Bitmap bitmap = getBitmapFromResources(id);
		int currentWidth = bitmap.getWidth();

		if (localWidth != currentWidth) {
			bitmap = LPUtils.createNewBitmap(bitmap, localWidth, localHeight);
		}
        //-------------------mod by zhaobin end----------------------
		String name = (String) lstDate.get(position).get("name");
		
		if(isHome){
			convertView = this.getViewHome(convertView,position,name,id,newChannel,bitmap);
		}else{
			convertView = this.getViewOther(convertView,position,name,id,newChannel,bitmap);
		}
		return convertView;
	}

	/**
	 * "我的首页"频道，getView方法
	 * */
	public View getViewHome(View convertView,final int position,String name,String id,String newChannel,Bitmap bitmap){
		convertView = LayoutInflater.from(context).inflate(R.layout.drop_grid_item, null);
		
		ImageView ivImage = (ImageView) convertView.findViewById(R.id.image_item);
		TextView tvName = (TextView) convertView.findViewById(R.id.text_item);
		ImageView ivDel = (ImageView) convertView.findViewById(R.id.del);
		ImageView ivNews = (ImageView) convertView.findViewById(R.id.new_add);
		
		ivImage.setImageBitmap(bitmap);
		tvName.setText(null != name ? name:"");
		
		if (isInEdit) {
				// 强推item和最后一个item
				if (position > (LPMid.getInstance().um_.data.remommendSize-1)  
						&& position != lstDate.size() - 1) {
					ivDel.setVisibility(View.VISIBLE);
				}
				
				//如果是"添加"不显示
				if (id.equalsIgnoreCase("menuitem_add")) {
					convertView.setVisibility(View.INVISIBLE);
				}else{
					convertView.setVisibility(View.VISIBLE);
				}
		} else {
			ivDel.setVisibility(View.GONE);
		}

		//判断是否显示新增channel的图标
		if(null != newChannel && "new".equalsIgnoreCase(newChannel)){
			if(LPMid.getInstance().um_.data.isSavedChannelId(id)){
				ivNews.setVisibility(View.GONE);
			}else{
				ivNews.setVisibility(View.VISIBLE);
			}
		}else{
			ivNews.setVisibility(View.GONE);
		}
		
		ivDel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				lstDate.remove(position);
				notifyDataSetChanged();
			}
		});
		
		if (isChanged) {
			if (position == holdPosition) {
				if (!ShowItem) {
					convertView.setVisibility(View.INVISIBLE);
				}
			}
		}
		
		return convertView;
	}
	
	/**
	 * 其他频道，getView方法
	 * */
	public View getViewOther(View convertView,int position,String name,String id,String newChannel,Bitmap bitmap){
		ViewHolder holder = null;
		if(convertView == null){
			convertView = LayoutInflater.from(context).inflate(R.layout.drop_grid_item, null);
			holder = new ViewHolder();
			holder.name = (TextView)convertView.findViewById(R.id.text_item);
			holder.image = (ImageView)convertView.findViewById(R.id.image_item);
			holder.delImage = (ImageView)convertView.findViewById(R.id.del);
			holder.ivNews = (ImageView) convertView.findViewById(R.id.new_add);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder)convertView.getTag();
		}
		
		//判断是否显示新增channel的图标
		if(null != newChannel && "new".equalsIgnoreCase(newChannel)){
			if(LPMid.getInstance().um_.data.isSavedChannelId(id)){
				holder.ivNews.setVisibility(View.GONE);
			}else{
				holder.ivNews.setVisibility(View.VISIBLE);
			}
		}else{
			holder.ivNews.setVisibility(View.GONE);
		}
		
		holder.name.setText(null != name ? name:"");
		holder.image.setImageBitmap(bitmap);
		holder.delImage.setVisibility(View.GONE);
		
		return convertView;
	}
	
	public class ViewHolder{
		TextView name;
		ImageView image;
		ImageView delImage;
		ImageView ivNews;
	}
	
	/**
	 * 获取图片，本地资源或者是离线资源
	 * */
	public static Bitmap getBitmapFromResources(String id) {
		if (bitmapCache.containsKey(id)) {
			return bitmapCache.get(id);
		}

		Bitmap bm = getBitmapFromResources(context, id);
		if (null == bm) {
			bm = BitmapFactory.decodeResource(context.getResources(),R.drawable.m_native);
		}
		bitmapCache.put(id, bm);
		return bm;
	}
	
	/**
	 * 进入编辑模式还是退出编辑模式
	 * @param isEdit
	 */
	public void stepIntoEditMode(boolean isEdit){
		//九宫格进入编辑状态
		isInEdit = isEdit;
		//this.isShowAdd = !isEdit;
		this.notifyDataSetChanged();
	}
	
    /**
     * 获取资源图片
     * 
     * @param context
     * @param resourcesName
     * @return
     */
    public final static Bitmap getBitmapFromResources(Context context, String resourcesName) {
        Bitmap bitmap = null;
        byte[] buffer = null;
        if (resourcesName == null)
            return bitmap;

		Object img = null;
		// 先补png后缀名。
		resourcesName = Utils.getPNGName(resourcesName);
		resourcesName = "m_"+resourcesName;
		// 插件资源。
		img = OffStoreDB.PLUGDB.find(resourcesName);
		if (img != null) {
			buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.PLUGROOT).concat(resourcesName));
			if (buffer != null) {
			    bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
			}
		}
		 
		// 离线资源
		if (bitmap == null) {
		//  img = OffStoreDB.OFFLINEDB.find(resourcesName);
		    String basePath = Utils.getFilePath(new File(OffStoreDownload.FILEROOT.concat(OffStoreDownload.OFFLINEROOT))
		    , resourcesName);
		    if (basePath != null) {
		        if(!basePath.endsWith("/")){
		            basePath += "/";
		        }
		        buffer = Utils.readFile(basePath.concat(resourcesName));
		        if (buffer != null) {
		            bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
		        }
		    }
		}
		
		// file：write写出的资源
		if (bitmap == null) {
		    buffer = Utils.readFile(OffStoreDownload.FILEROOT.concat(OffStoreDownload.WRITEROOT).concat(resourcesName));
		    if (buffer != null) {
		        bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
		    }
		}
		// 资源文件
		if (bitmap == null) {
		    // 如果sql中没有存储对应的图片，则将后缀去掉，在资源文件里面搜索
		    if (resourcesName.endsWith(".png")) {
		        resourcesName = resourcesName.substring(0, resourcesName.lastIndexOf(".png"));
		    }
		    resourcesName = resourcesName.toLowerCase();
		    int resourcesId = Utils.getResourcesId(context, resourcesName, "drawable");
		    if (resourcesId != 0) {
		        bitmap = BitmapFactory.decodeResource(context.getResources(), resourcesId);
		    }
		}

        return bitmap;
    }

}
